<?php
namespace app\sso\controller;

use think\Response;
use think\facade\View;
use think\facade\Validate;
use app\common\util\ReturnCode;
use app\common\service\JwtService;
use app\common\library\Auth as AuthService;

class Api extends Base
{
    public function getUserInfo(): Response {
        // 使用buildSuccess方法返回用户信息，$this->userInfo包含当前用户信息
        return $this->buildSuccess([
            'userInfo' => $this->request->userInfo
        ], '');
    }
    
    public function login(): Response {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$username) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少用户名!');
        }
        if (!$password) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少密码!');
        }
        // // 检查是否超过登录失败限制
        // $maxAttempts = 5; // 最大允许失败次数
        // if ($this->isLoginBlocked($username, $maxAttempts)) {
        //     return $this->buildFailed(ReturnCode::LOGIN_ERROR, '登录失败次数过多，请稍后再试');             
        // }
        // // 检查IP是否被限制
        // $ip = $this->request->ip();  // 获取用户IP
        // if ($this->isIpRestricted($ip)) {
        //     return $this->buildFailed(ReturnCode::LOGIN_ERROR, '您的IP已被限制，请稍后再试');   
        // }   
        // 登录逻辑...
        $AuthService = new AuthService(); 
        $result = $AuthService->login($username, $password);
        if (!$result) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, $AuthService->getError());
        }
        $token = $AuthService->getToken();
        // 验证JWT
        $decoded = JwtService::validateUserToken($token);  // 使用JwtService解码token
        if (!$decoded) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '登录失败');
        }
        return $this->buildSuccess([
            'token' => $token,
            'userInfo' => $decoded->user
        ], '登录成功');
    }
    
    public function logout(): Response {
        // 清除session或token等认证信息
        // 这里可以根据实际情况进行处理，例如清除session或token等认证信息
        // 这里只是一个示例，实际情况可能需要根据具体需求进行处理
        if (!$this->request->isPost()) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '请求方式错误');
        }
        $AuthService = new AuthService();
        $result = $AuthService->logout();
        return $this->buildSuccess([], '退出登录成功');   
    }

    public function register(): Response {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        if (!$username) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少用户名!');
        }
        if (!$password) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少密码!');
        }
        // 注册逻辑...
        $AuthService = new AuthService();
        $result = $AuthService->register($username, $password);
        if (!$result) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, $AuthService->getError());
        }
        $token = $AuthService->getToken();
        if (!$token) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '注册失败');
        }
        // 验证JWT
        $decoded = JwtService::validateUserToken($token);  // 使用JwtService解码token
        if (!$decoded) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '注册失败');
        }           

        // 注册成功后返回成功响应
        return $this->buildSuccess([], '注册成功');
    }
    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少参数');
        }
        if ($type == 'mobile') {
            if (!$mobile) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少手机号');
            }
        } else {
            if (!$email) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少邮箱');
            }
        }


        $validate = \think\facade\Validate::rule([
            'newpassword'  => 'require|regex:\S{6,30}'
        ]);
        $data = [
            'newpassword'  => $newpassword
        ];        
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, $validate->getError());
        }
        if ($type == 'mobile') {
            if($this->request->userInfo->mobile!=$mobile){  
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '账号手机号不一致');
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) { 
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '手机格式不正确');
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户不存在');
            }
            // 短信验证码验证 todo
            // $ret = Sms::check($mobile, $captcha, 'resetpwd');
            // if (!$ret) {
            //     return $this->buildFailed(ReturnCode::LOGIN_ERROR, '短信验证码不正确');
            // }
            // Sms::flush($mobile, 'resetpwd');
        } else {
            if($this->request->userInfo->email!=$email){  
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '账号邮箱不一致');
            }
            if (!Validate::is($email, "email")) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '邮箱格式不正确');
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户不存在');
            }
            // 邮箱验证码验证 todo
            // $ret = Ems::check($email, $captcha, 'resetpwd');
            // if (!$ret) {
            //     return $this->buildFailed(ReturnCode::LOGIN_ERROR, '邮箱验证码不正确');
            // }
            // Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $AuthService = new AuthService();
        $AuthService->direct($user->id);
        $ret = $AuthService->changepwd($newpassword, '', true);
        if ($ret) {
            return $this->buildSuccess([], '重置密码成功');
        } else {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, $AuthService->getError());
        }
    }

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="type", type="string", required=true, description="类型")
     * 
     * @return Response
     */
    public function sendsmscode()           
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        if ($type =='mobile') {
            if (!$mobile) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少手机号');
            }
            if (!Validate::regex($mobile, "^1\d{10}$")) { 
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '手机格式不正确');
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户不存在');
            }
            // 发送短信验证码
                return $this->buildSuccess(['token' => $this->request->buildToken('__token__', 'sha1')], '发送成功');
            // $ret = Sms::send($mobile, 'resetpwd');   
            // if ($ret) {
            //     return $this->buildSuccess([], '发送成功');
            // } else {
            //     return $this->buildFailed(ReturnCode::LOGIN_ERROR, '发送失败');         
            // }
        }
        if ($type =='email') {
            if (!$email) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少邮箱');
            }
            if (!Validate::is($email, "email")) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '邮箱格式不正确');
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户不存在');
            }
            // 发送邮箱验证码
            $ret = Ems::send($email, 'resetpwd');   
            if ($ret) {
                return $this->buildSuccess([], '发送成功');
            } else {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '发送失败');         
            }
        }
    }
}
